package com.pansoft.openplanet.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.utils.ResStringUtil;
import com.pansoft.kline.adapter.SimpleFragmentPagerAdapter;
import com.pansoft.kline.fragment.KLineChartFragment;
import com.pansoft.kline.fragment.TimeLineChartFragment;
import com.pansoft.kline.model.IndexSelectEvent;
import com.pansoft.kline.model.KIndexSelectEvent;
import com.pansoft.kline.widget.KindexPopupWindow;
import com.pansoft.klinelib.chart.KLineView;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.fragment.TransactionListFragment;
import com.pansoft.openplanet.manager.CoinMarketIdManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_15_MINUTE;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_3_DAY;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_DAY;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_HOUR;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_MINUTE;

//import com.github.mikephil.charting.charts.LineChart;
//import com.pansoft.openplanet.util.ChartUtils;

/**
 * 交易折线图
 * Created by yqs on 2018/06/05
 */

public class TradeLineActivity extends TCBaseActivity implements View.OnClickListener {

    //全部
    public static final int TRANSACTION_TYPE_ALL = 1;
    //转入
    public static final int TRANSACTION_TYPE_IN = 3;
    //转出
    public static final int TRANSACTION_TYPE_OUT = 2;
    //失败
    public static final int TRANSACTION_TYPE_FAIL = 4;

    private ImageView ivBack;
    private TextView tvTitle;
    private TabLayout tablayout;
    private ViewPager viewpager;
    private int mode;
    private Button butGather;
    private Button butTrans;
    private String address;
    private AssetListBean assetListBean;

    private TabLayout klineTabLayout;
    private ViewPager viewPager;
    private ProgressDialog progressDialog;
    private String marketId;
    private ImageView ivRefresh;
//    private ConstraintLayout clIndex;
//    private ImageView ivIndexTopRight, ivIndexBottomRight;
    /**
     * 加载各指标图表
     **/
    private List<Fragment> fragments = new ArrayList<>();
    private SimpleFragmentPagerAdapter simpleFragmentPagerAdapter;

    //    private String[] titles = new String[]{"全部", "转出", "转入", "失败"};

    private String[] titles = new String[]{ResStringUtil.getString(R.string.open_planet_asset_trade_line_all)
            , ResStringUtil.getString(R.string.open_planet_asset_trade_line_transfer_out), ResStringUtil.getString(R.string.open_planet_asset_trade_line_transfer_in)};


    /**
     * @param name    账户名
     * @param mode    MODE_ETH, MODE_BTC等
     * @param address 账户地址
     * @param accountType  账户类型2是冷钱包
     */
    public static void startTradeLineActivity(Context context, int mode, String name,
                                              String address, String walletIcon, String balance, AssetListBean assetListBean,
                                              String filePath, int accountType) {
        Intent intent = new Intent(context, TradeLineActivity.class);
        //eth btc ipassetconstanst
        intent.putExtra("mode", mode);
        //钱包名 用来当标题
        intent.putExtra("name", name);
        //钱包地址
        intent.putExtra("address", address);
        //余额
        intent.putExtra("balance", balance);
        //图标
        intent.putExtra("walletIcon", walletIcon);
        //代币的bean
        intent.putExtra("assetBean", assetListBean);
        //keystore文件路径 给交易能量币使用
        intent.putExtra("filePath", filePath);
        //账户类型2是冷钱包
        intent.putExtra("accountType", accountType);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_trade_line);
        assetListBean = (AssetListBean) getIntent().getSerializableExtra("assetBean");
        address = getIntent().getStringExtra("address");
        mode = getIntent().getIntExtra("mode", 0);
        marketId = CoinMarketIdManager.getMarketId(mode);
        initView();
        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }


    private void initView() {
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);


//        chart = (LineChart) findViewById(R.id.chart);
        tablayout = (TabLayout) findViewById(R.id.tablayout);
        viewpager = (ViewPager) findViewById(R.id.viewpager);
        ivBack.setOnClickListener(this);
        butGather = (Button) findViewById(R.id.but_gather);
        butGather.setOnClickListener(this);
        butTrans = (Button) findViewById(R.id.but_trans);
        butTrans.setOnClickListener(this);
//        GradientDrawable myGrad = (GradientDrawable) butTrans.getBackground();
//        myGrad.setColor(getResources().getColor(R.color.tradeline_button_shape_color1));
//        ChartUtils.initChart(chart);
        for (int i = 0; i < titles.length; i++) {
            tablayout.addTab(tablayout.newTab().setText(titles[i]));
        }
        tablayout.setupWithViewPager(viewpager);

        progressDialog = new ProgressDialog(this);
        klineTabLayout = (TabLayout) findViewById(R.id.tab);
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        setUpKLineFragmentAdapter();
        viewPager.setAdapter(simpleFragmentPagerAdapter);
        klineTabLayout.setupWithViewPager(viewPager);
        ivRefresh = (ImageView) findViewById(R.id.iv_refresh);
        ivRefresh.setOnClickListener(this);
        initButton();
        //处理K线指标弹窗
        initKIndexView();
        //处理MA,Boll指标弹窗
        initIndexView();
    }

    private void initButton() {
        if (mode == IPAssetsConstant.CHAIN_ID_TURBOCHAIN && assetListBean != null) {
            //pwr 代币转账暂时屏蔽掉
            findViewById(R.id.ll_bottom).setVisibility(View.GONE);
        }
    }

    private void initViewPager() {
        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), titles, address, mode, assetListBean));

    }

    private void initData() {
        if (mode == IPAssetsConstant.CHAIN_ID_BTC) {
            titles = new String[]{ResStringUtil.getString(R.string.open_planet_asset_trade_line_all)
                    , ResStringUtil.getString(R.string.open_planet_asset_trade_line_transfer_out)
                    , ResStringUtil.getString(R.string.open_planet_asset_trade_line_transfer_in)};
        }
        initViewPager();
        String titleName = getIntent().getStringExtra("name");
        tvTitle.setText(titleName);

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.but_gather) {

            if (getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH) == IPAssetsConstant.CHAIN_ID_TURBOCHAIN) {
                //能量币转入界面
                Intent intent = new Intent(this, EnergyQRCodeActivity.class);
                startActivity(intent);
                return;
            }
            //收款
            if (assetListBean != null) {
                BarcodeReceiveActivity.start(this, getIntent().getStringExtra("name"),
                        getIntent().getStringExtra("address"),
                        getIntent().getStringExtra("walletIcon"),
                        assetListBean.getName(),
                        assetListBean.getAddress(),
                        Integer.valueOf(assetListBean.getBlockChainID()),
                        assetListBean.getId());
            } else {
                BarcodeReceiveActivity.start(this, getIntent().getStringExtra("name"),
                        getIntent().getStringExtra("address"),
                        getIntent().getStringExtra("walletIcon"),
                        "", "", getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH), "");
            }

        } else if (id == R.id.but_trans) {
            //如果是涡链，隐藏下方的交易按钮
            if (getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH) == IPAssetsConstant.CHAIN_ID_TURBOCHAIN) {
                Intent intent = new Intent(this, TransferActivity.class);
                intent.putExtra("myaddress", getIntent().getStringExtra("address"));
                intent.putExtra("balance", getIntent().getStringExtra("balance"));
                intent.putExtra("filePath", getIntent().getStringExtra("filePath"));
                startActivity(intent);
                return;
            }

            //转账
            NewTransferActivity.start(this, getIntent().getStringExtra("name"),
                    //上一个界面传来的数据
                    getIntent().getIntExtra("mode", IPAssetsConstant.CHAIN_ID_ETH),
                    getIntent().getStringExtra("address"),
                    getIntent().getStringExtra("balance"), assetListBean,
                    getIntent().getIntExtra("accountType", 0));
        } else if (id == R.id.iv_refresh) {
            refreshKChart();
        }
    }


    public static class MyPagerAdapter extends FragmentPagerAdapter {
        String[] titles;
        String address;
        int mode;
        AssetListBean assetListBean;

        public MyPagerAdapter(FragmentManager fm, String[] titles, String address, int mode, AssetListBean assetListBean) {
            super(fm);
            this.titles = titles;
            this.address = address;
            this.mode = mode;
            this.assetListBean = assetListBean;
        }

        @Override
        public Fragment getItem(int position) {

            Bundle bundle = new Bundle();

            TransactionListFragment fragment = new TransactionListFragment();
            switch (position) {
                case 0:
                    bundle.putInt("type", TRANSACTION_TYPE_ALL);
                    break;
                case 1:
                    bundle.putInt("type", TRANSACTION_TYPE_OUT);
                    break;
                case 2:
                    bundle.putInt("type", TRANSACTION_TYPE_IN);
                    break;
                case 3:
                    bundle.putInt("type", TRANSACTION_TYPE_FAIL);
                    break;
                default:
                    bundle.putInt("type", TRANSACTION_TYPE_ALL);
                    break;
            }

            bundle.putString("address", address);
            bundle.putInt("mode", mode);
            if (assetListBean != null) {
                bundle.putString("tokenId", assetListBean.getId());
            }

            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getCount() {
            return titles.length;
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

    /**
     * 1分K，日K等指标选择
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveKIndexSelectedEvent(KIndexSelectEvent event) {
        KindexPopupWindow.setTabIndexText(TradeLineActivity.this, klineTabLayout, event.getIndexName());
        ((KLineChartFragment) fragments.get(4)).reloadData(event.getIndex());
    }

    /**
     * MA， KDJ等指标选择, 更改当前界面视图
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIndexSelectedEvent(IndexSelectEvent event) {
        switch (event.getIndex()) {
            case "MA":
                KLineView.CHART_MAIN_INDEX = "MA";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMa();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMa();
                }
                break;
            case "BOLL":
                KLineView.CHART_MAIN_INDEX = "BOLL";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showBoll();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showBoll();
                }
                break;
            case "MACD":
                KLineView.CHART_SUB_INDEX = "MACD";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMacd();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMacd();
                }
                break;
            case "KDJ":
                KLineView.CHART_SUB_INDEX = "KDJ";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showKdj();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showKdj();
                }
                break;
            default:
                break;
        }
    }

    private void setUpKLineFragmentAdapter() {
        Fragment[] fragmentArray = {TimeLineChartFragment.newInstance(K_LINE_TYPE_MINUTE, marketId, true), KLineChartFragment.newInstance(K_LINE_TYPE_15_MINUTE, marketId, true),
                KLineChartFragment.newInstance(K_LINE_TYPE_HOUR, marketId, true), KLineChartFragment.newInstance(K_LINE_TYPE_DAY, marketId, true),
                KLineChartFragment.newInstance(K_LINE_TYPE_3_DAY, marketId, true)};
        fragments.clear();
        fragments.addAll(Arrays.asList(fragmentArray));
        String[] titleArray = getResources().getStringArray(R.array.array_chart_k_index);
        List<String> titles = Arrays.asList(titleArray);
        //viewPager.setOffscreenPageLimit(fragments.length);
        simpleFragmentPagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), fragments, titles);
    }

    private void initKIndexView() {
        final View tabItemView = LayoutInflater.from(this).inflate(R.layout.chart_layout_tab_item, null, false);
        klineTabLayout.getTabAt(4).setCustomView(tabItemView);
        klineTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 4) {
                    KindexPopupWindow.setKIndexTabSelected(TradeLineActivity.this, klineTabLayout);
                } else {
                    KindexPopupWindow.setKIndexTabUnSelected(TradeLineActivity.this, klineTabLayout);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (tab.getPosition() == 4) {
                    KindexPopupWindow.setKIndexTabShowPop(TradeLineActivity.this, klineTabLayout);
                    new KindexPopupWindow(TradeLineActivity.this,
                            TradeLineActivity.this.getWindow().getDecorView(), klineTabLayout, ((TextView) tab.getCustomView().findViewById(R.id.tv_K_index)).getText().toString());
                }
            }
        });
    }

    private void initIndexView() {
//        clIndex = (ConstraintLayout) findViewById(R.id.cl_index);
//        ivIndexTopRight = (ImageView) findViewById(R.id.iv_full_right_top_triangle);
//        ivIndexBottomRight = (ImageView) findViewById(R.id.iv_full_right_bottom_triangle);
//
//        clIndex.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ivIndexTopRight.setVisibility(View.VISIBLE);
//                ivIndexBottomRight.setVisibility(View.INVISIBLE);
//                new ChartIndexPopupWindow(TradeLineActivity.this,
//                        TradeLineActivity.this.getWindow().getDecorView(), clIndex);
//            }
//        });
    }

    private void refreshKChart() {
        if (viewPager.getCurrentItem() == 0) {
            ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData();
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        } else if (viewPager.getCurrentItem() == 1){
            ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData();
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        } else if (viewPager.getCurrentItem() == fragments.size() - 1) {
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
        } else {
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        }
    }
}
